var express = require('express');
var axios =require('axios');
var router = express.Router();
const appid='wx05545647f2297019';
const secret='c971f3969f5cdfae379eb86308e7e4fe';
const baseUrl="https://api.weixin.qq.com/sns/jscode2session";
var errRes=function(res,message){
   res.send({
    status:-1,
    message:message
  })
}
var urlJoin=function(url,query){
  var s='?'
  for(i in query){
    s+=i+'='+query[i]+'&'
  }
  return url+s
}

var ajaxUrl=function(url,methods,data,succssBack,errorBack){
  axios({
    method:methods,
    url:url,
    data:data,
  }).then(res=>{
    succssBack(res)
  }).catch(err=>{
    errorBack(err)
  })
}

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

router.get('/getOpenId',function(req,res){
  console.log(req.query);
  var js_code=req.query.js_code;
  if(js_code==undefined||js_code==''){
    errRes(res,'缺少参数js_code');
    return
  }
  var query={
    grant_type:'authorization_code',
    appid:appid,
    secret:secret,
    js_code:js_code
  }
//  urlJoin(baseUrl,query)
  ajaxUrl(urlJoin(baseUrl,query),'get',{},function(resp){
    res.send({
      status:0,
      message:"获取成功",
      data:resp.data
    })
  },function(err){
    res.send(err)
    console.log(err)
  })

})

module.exports = router;
//♞